package com.woniumall.service.impl;

import com.woniumall.dao.AddressDao;
import com.woniumall.dao.UserDao;
import com.woniumall.pojo.Address;
import com.woniumall.pojo.Massage;
import com.woniumall.pojo.User;
import com.woniumall.service.AddressService;
import com.woniumall.service.UserService;
import com.woniumall.util.MailUtils;
import com.woniumall.util.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;

/**
 * @auther linke
 * @create 2021-10-29 16:52
 */

public class AddressServiceImpl implements AddressService {
    private  SqlSession sqlSession;
    private  AddressDao addressDao;


    @Override
    public List<Address> findAllByUserId(int userId) {
        sqlSession = sqlSessionUtil.sqlSession();
        addressDao = sqlSession.getMapper(AddressDao.class);
        List<Address> addressList = addressDao.findAllByUserId(userId);

        sqlSession.close();
        return addressList;
    }

    @Override
    public Address findById(int id) {
        sqlSession = sqlSessionUtil.sqlSession();
        addressDao = sqlSession.getMapper(AddressDao.class);

        Address address = addressDao.findById(id);
        sqlSession.close();
        System.out.println(address);
        return address;
    }
    //添加地址
    @Override
    public int addressUp(Address add) {
        sqlSession = sqlSessionUtil.sqlSession();
        addressDao = sqlSession.getMapper(AddressDao.class);

        System.out.println(add);
        int addressid = addressDao.add(add);
        sqlSession.commit();
        sqlSession.close();
        return addressid;
    }

    @Override
    public void updateType(int id,int userid) {
        sqlSession = sqlSessionUtil.sqlSession();
        addressDao = sqlSession.getMapper(AddressDao.class);
        //查询所有地址
        List<Address> list = addressDao.findAllByUserId(userid);
        for (Address address : list) {//遍历当前用户所有地址，将状态修改为0
            addressDao.updateTypeById(address.getId(),"0");
            sqlSession.commit();

        }
        addressDao.updateTypeById(id,"1");//将新加入的地址状态变更为1
        sqlSession.commit();

    }

    @Override
    public int del(int id) {
        sqlSession = sqlSessionUtil.sqlSession();
        addressDao = sqlSession.getMapper(AddressDao.class);
        int row = addressDao.del(id);
        sqlSession.commit();
        sqlSession.close();
        return row;
    }
}
